int[] data = new int[10];

Answer:

  1. What is the length of the array data? 10
  2. What are the indexes of data? 0, 1, 2, ..., 8, 9

Bounds Checking

Recall that:

The length of an array is how many cells it has. An array of length N has cells indexed 0..(N-1)

Indexes must be an integer type. It is OK to have spaces around the index of an array, for example data[1] and data[ 1 ] are exactly the same as far as the compiler is concerned. It is not legal to refer to a cell that does not exist.

Say that an array were declared:

int[] data = new int[10];

Here are some subscripted variables of this array:

data[ -1 ] always illegal
data[ 10 ] illegal   (given the above declaration)
data[ 1.5 ] always illegal
data[ 0 ] always OK
data[ 9 ] OK   (given the above declaration)

If your program contains an expression that is always illegal, it will not compile. But often the size of an array is not known to the compiler. The size of an array often is determined by data at run time. Since the array is constructed as the program is running, the compiler does not know its length and can't predict some errors. If, when it is running, the program refers to a cell that does not exist, an exception is thrown, and (usually) the program is terminated.

As a Java program is running, each time an array index is used it is checked to be sure that it is OK. This is called bounds checking, and is extremely important for catching errors.

QUESTION 6:

Here is a declaration of another array:

double[] scores = new double[25];

Which of the following are legal?

scores[ 0 ] scores[1] scores[ -1 ]
scores[ 10] scores[ 25 ] scores[ 24 ]